//
//  PurchaseHistoryVM.swift
//  LeTu
//
//  Created by gy on 2023/12/8.
//

import Foundation

class PurchaseHistoryVM {
    
    /// 数据分页
    private var pageNum = 1
    /// 数据长度
    private(set) var pageSize = 20
    /// 关键词
    private var keyword: String?
    /// 购买记录
    private(set) var sourceArr = [PurchaseHistoryModel]()

    // MARK: - 获取购买记录
    func getCollects(isLoad: Bool, completeHandle: @escaping NetworkRequestHandle) {
        
        var pageNum = self.pageNum
        pageNum = isLoad ? pageNum + 1 : 1
        
        var param: [String : Any] = [String : Any]()
        param["page"] = pageNum
        param["pageSize"] = pageSize
        
        apiProvider.request(api: .getPurchaseHistory(params: param)) { [weak self] json, jsonArr, code in
            MYLog("购买记录信息：", json)
                        
            var dialog = DialogMessage()

            guard let strongSelf = self, let response = Mapper<ResponseModel>().map(JSON: json) else { return completeHandle(dialog) }
            dialog.code = response.code
            dialog.message = response.msg
            guard dialog.code == 200, let dataDic = response.data as? [[String: Any]] else { return completeHandle(dialog) }
            
            strongSelf.pageNum = pageNum
            let tempList = Mapper<PurchaseHistoryModel>().mapArray(JSONArray: dataDic)
            if isLoad {
                strongSelf.sourceArr = strongSelf.sourceArr + tempList
            } else {
                strongSelf.sourceArr = tempList
            }
            
            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }
        
    }
    
}

